import React, { useState } from 'react'
import './index.less'
const StatePage = () => {
  const [num, setNum] = useState(0)
  const numHandle = () => {
    setNum(num + 1)
  }
  const [list, setList] = useState([
    {
      content: '我是list'
    }
  ])
  const addListHandle = ()=>{
    setList((preData)=>{
      const newArr = [{
        content: '哈哈哈啊哈'
      }]
      // 结构复制才会实时更新
      return [...preData,...newArr]
    })
  }
  const [obj,setObj] = useState<any>({
    name:'学生',
    age:18
  })
  const iptChange = (event:any,type:any)=>{
    const _value = event.target.value
    obj[type] = _value
    setObj({...obj})
  }
  return (
    <div className='state_page'>
      <h1>useState的使用</h1>
      <div className='box'>
        常量的state：{num} <button onClick={numHandle}>改变Num</button>
      </div>
      <div className='box'>
        数组的state <button onClick={addListHandle}>添加List</button>
      </div>
      <div className='list'>
        {
          list.map((item, index) => {
            return (<div className="list_item" key={index}>
              {item.content}{index + 1}
            </div>)
          })
        }
      </div>

      <div className='box'>
        对象的state
      </div>
      <div>
        <input type="text" value={obj.name} onChange={(event)=>iptChange(event,'name')}/>
        <input type="number" value={obj.age} onChange={(event)=>iptChange(event,'age')}/>
      </div>
    </div>
  )
}

export default StatePage